﻿
using Se.Common;
using Se.Model;
using Se.Model.GameModel.Character;
using Se.Net.Sockets;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Se.Model.Host
{
    /// <summary>
    /// Session
    /// </summary>
    public class SocketSession
    {
        /// <summary>
        /// Session参数
        /// </summary>
        private Dictionary<string, object> _parameters = new Dictionary<string, object>();
        /// <summary>
        /// Id
        /// </summary>
        public string SessionId { get; private set; }
        /// <summary>
        /// Socket
        /// </summary>
        public ExSocket Socket { get; private set; }
        /// <summary>
        /// Host
        /// </summary>
        public SocketHost Host { get; set; }
        /// <summary>
        /// Player
        /// </summary>
        public Player Player { get; private set; }
        /// <summary>
        /// Account
        /// </summary>
        public Account Account { get; set; }
        /// <summary>
        /// 状态
        /// </summary>
        public SessionState State { get; set; }

        /// <summary>
        /// 自定义参数
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object this[string key]
        {
            get
            {
                if (this._parameters.ContainsKey(key)) return this._parameters[key];
                return null;
            }
            set
            {
                this._parameters[key] = value;
            }
        }

        public SocketSession(ExSocket exSocket, SocketHost host, string sessionId)
        {
            if (exSocket == null)
                throw new ArgumentNullException("exSocket", "the exsocket of SocketSession can't be null");
            this.SessionId = sessionId;
            this.Socket = exSocket;
            this.Host = host;
            this.Host.Listener.SocketDisConnected += SocketDisConnected;
            this.State = SessionState.Disconnect;
        }
        /// <summary>
        /// 设置Player
        /// </summary>
        /// <param name="player"></param>
        public void SetPlayer(Player player)
        {
            this.Player = player;
        }

        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="bs"></param>
        public void SendToClient(byte[] bs)
        {
            this.Host.Listener.Send(this.Socket, bs);
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="exSocket"></param>
        private void SocketDisConnected(ExSocket exSocket)
        {
            this.State = SessionState.Disconnect;
            this.Player = null;
        }
    }
}
